import Chatroom from '../../vendor/NIM_Web_Chatroom_v5.4.0.js'
import * as iconBase64Map from '../../utils/imageBase64.js'
import { formatTime, generateRichTextNode, generateImageNode, generateFingerGuessImageFile } from '../../utils/util.js'
const app = require('../../live.js')
var socketOpen = false;
var SocketTask2 = {};
var integralTimeout = null;
var goodsInterval = null;
var interval1 = null;
var interval2 = null;
var interval3 = null;
var interval4 = null;
var interval5 = null;
var j = 0; //记录点击次数
var xinFlag = true; //飘心动画(防止频率太高)
Page({
  data: {
    addGoodsB: false,
    couponFlag: true,
    giftFlag: false,
    cursorSpacingB: false,
    couponB1: false,//优惠券(8元)
    couponB2: false,//优惠券(50元)
    couponB3: false,//优惠券(100元)
    couponB4: false,//优惠券(200元)
    couponB5: false,//优惠券(500元)
    currentTime1: 10,
    currentTime2: 10,
    currentTime3: 10,
    currentTime4: 10,
    currentTime5: 10,
    time1: 10,
    time2: 10,
    time3: 10,
    time4: 10,
    time5: 10,
    xinArr: [{ src: '../../img/xin02.png', animation: 'top-animation', xinB: false }, { src: '../../img/xin06.png', animation: 'top-animation2', xinB: false }, { src: '../../img/xin03.png', animation: 'top-animation3', xinB: false }, { src: '../../img/xin05.png', animation: 'top-animation4', xinB: false }, { src: '../../img/xin07.png', animation: 'top-animation5', xinB: false }, { src: '../../img/xin04.png', animation: 'top-animation6', xinB: false }, { src: '../../img/xin02.png', animation: 'top-animation', xinB: false }, { src: '../../img/xin03.png', animation: 'top-animation2', xinB: false }, { src: '../../img/xin04.png', animation: 'top-animation3', xinB: false }, { src: '../../img/xin05.png', animation: 'top-animation4', xinB: false }, { src: '../../img/xin02.png', animation: 'top-animation5', xinB: false }, { src: '../../img/xin07.png', animation: 'top-animation6', xinB: false }],//飘心对象
    integralB: false, //积分动画
    purchaserB: false, //购买者动态动画
    openGiftB: false, //打开礼物动画
    giftB: false, //礼物从天降动画
    endB: true, //直播结束
    goodsListB: false, //商品列表
    inputB: true, //是否显示输入框

    defaultAvatar: '', //用户默认头像（以下是聊天部分）
    currentTab: 0,//顶部当前索引
    roomInfo: {}, // 房间信息 {announcement, broadcasturl, createtime，creator，ext，name，onlineusercount，roomid，status}
    ownerInfo: {}, // 主播信息 {account, avatar,blacked,chatroomId,custom,gaged,nick,online,tempMuted,tempMuteDuration,type,updateTime,valid}
    onlineMember: [], // 在线成员 [{account,avatar,nick,type}]
    iconBase64Map: {}, // base64 icon
    inputValue: '', // 发送的文本内容
    focusFlag: false,//控制输入框失去焦点与否
    emojiFlag: false,//emoji键盘标志位
    moreFlag: false, // 更多功能标志
    messageArr: [{ text: '欢迎来到江南布衣直播间,文明发言,共建和谐社区！', nick: '温馨提示', color: '#ffd78b'}], // 渲染的数据
    accountMap: {}, // 存储了账号map，目的是账号去重
    animation: null,
    scrollTop: 0,
    messageWrapperMaxHeight: null, // 消息列表容器最大高度

    pulling: false, //以下是直播部分
    livePlayerContext: {},
    src: '', //	音视频地址。目前仅支持 flv, rtmp 格式
    mode: 'live', // live（直播），RTC（实时通话）
    autoplay: true,
    muted: false,
    orientation: 'vertical', // 画面方向，可选值有 vertical，horizontal
    objectFit: 'fillCrop', // 填充模式，可选值有 contain，fillCrop
  },

  // 购买动态动画
  purchaserAnimation: function () {
    var that = this
    that.setData({
        purchaserB: true
      })
    setTimeout(function () {
      that.setData({
        purchaserB: false
      })
    }, 1300)
  },

  // 礼包动画
  giftAnimation: function () {
    var that = this
    this.setData({
      giftB: true,
      giftFlag: true
    })
  },

  // 关闭礼物
  giftHide: function () {
    this.setData({
      giftB: false,
    })
  },

  // 积分动画
  integralAnimation: function () {
    var that = this
    that.setData({
      integralB: true
    })
    setTimeout(function () {
      that.setData({
        integralB: false
      })
    }, 6000)
  },

  // 飘心动画
  xinAnimation: function () {
    var that = this
    if (xinFlag) {
      var xinB = "xinArr[" + j + "].xinB"
      // 点赞
      that.toZan()
      for (var i = 0; i < that.data.xinArr.length; i ++ ) {
        if (!that.data.xinArr[j].xinB) {
          that.setData({
            [xinB]: true
          })
          setTimeout(function () {
            that.setData({
              [xinB]: false
            })
          }, 2100)
        }
      }
      j++
      if (j > that.data.xinArr.length-1 ){
        j = 0;
      }
      xinFlag = false
      setTimeout(function () {
        xinFlag = true
      },300)
    }
  },

  // 显示商品列表
  goodsListShow: function () {
    this.setData({
      goodsListB: true
    })
  },


  // 打开礼物
  openGiftShow: function () {
    this.setData({
      openGiftB: true,
      giftB: false
    })
  },

  // 关闭礼物
  openGiftHide: function () {
    this.setData({
      openGiftB: false,
    })
  },

  // 关闭商品列表
  goodsListHide: function () {
    this.setData({
      goodsListB: false
    })
  },

  // 显示输入框
  inputShow: function () {
    this.setData({
      inputB: false
    })
  },

  // 隐藏输入框
  inputHide: function () {
    this.setData({
      inputB: true
    })
  },

  // 隐藏优惠券
  couponHide1: function () {
    var that = this;
    clearInterval(interval1)
    that.setData({
      currentTime1: 10,
      couponB1: false,
      time1: 10
    })
  },
  couponHide2: function () {
    var that = this;
    clearInterval(interval2)
    that.setData({
      currentTime2: 10,
      couponB2: false,
      time2: 10
    })
  },
  couponHide3: function () {
    var that = this;
    clearInterval(interval3)
    that.setData({
      currentTime3: 10,
      couponB3: false,
      time3: 10
    })
  },
  couponHide4: function () {
    var that = this;
    clearInterval(interval4)
    that.setData({
      currentTime4: 10,
      couponB4: false,
      time4: 10
    })
  },
  couponHide5: function () {
    var that = this;
    clearInterval(interval5)
    that.setData({
      currentTim5: 10,
      couponB5: false,
      time5: 10
    })
  },
  

  /**
   * 发送文本
   */
  inputSend2(e) {
    let text = this.data.inputValue;
    this.sendRequest(text)
  },

  // 退出直播
  return: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  // 倒计时
  countDown1:function () {
    var that = this
    var currentTime1 = that.data.currentTime1
    that.setData({
      couponB1: true
    })
    clearInterval(interval1)
    interval1 = setInterval(function () {
      currentTime1--;
      that.setData({
        time1: currentTime1
      })
      console.log("currentTime1"+currentTime1)
      if (currentTime1 <= 0) {
        clearInterval(interval1)
        that.setData({
          currentTime1: 10,
          couponB1: false,
          time1: 10
        })
      }
    }, 1000)
  },
  countDown2: function () {
    var that = this
    var currentTime2 = that.data.currentTime2
    that.setData({
      couponB2: true
    })
    clearInterval(interval2)
    interval2 = setInterval(function () {
      currentTime2--;
      that.setData({
        time2: currentTime2
      })
      if (currentTime2 <= 0) {
        clearInterval(interval2)
        that.setData({
          currentTime2: 10,
          couponB2: false,
          time2: 10
        })
      }
    }, 1000)
  },
  countDown3: function () {
    var that = this
    var currentTime3 = that.data.currentTime3
    that.setData({
      couponB3: true
    })
    clearInterval(interval3)
    interval3 = setInterval(function () {
      currentTime3--;
      that.setData({
        time3: currentTime3
      })
      if (currentTime3 <= 0) {
        clearInterval(interval3)
        that.setData({
          currentTime3: 10,
          couponB3: false,
          time3: 10
        })
      }
    }, 1000)
  },
  countDown4: function () {
    var that = this
    var currentTime4 = that.data.currentTime4
    that.setData({
      couponB4: true
    })
    clearInterval(interval4)
    interval4 = setInterval(function () {
      currentTime4--;
      that.setData({
        time4: currentTime4
      })
      if (currentTime4 <= 0) {
        clearInterval(interval4)
        that.setData({
          currentTime4: 10,
          couponB4: false,
          time4: 10
        })
      }
    }, 1000)
  },
  countDown5: function () {
    var that = this
    var currentTime5 = that.data.currentTime5
    that.setData({
      couponB5: true
    })
    clearInterval(interval5)
    interval5 = setInterval(function () {
      currentTime5--;
      that.setData({
        time5: currentTime5
      })
      if (currentTime5 <= 0) {
        clearInterval(interval5)
        that.setData({
          currentTime5: 10,
          couponB5: false,
          time5: 10
        })
      }
    }, 1000)
  },

  // 点赞
  toZan: function () {
    
   var that = this
    wx.request({
      url: app.pageConfig.jnbyUrl +'/sunday/small/live/zan',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        liveId: this.data.liveId
      },
      success: function (res) {
        console.log(res)
        var code = res.data.code;
        if (code == 0){
          that.setData({
            zanNum: Number(that.data.zanNum) + 1
          })
        }
      },
      complete: function () {
        
      }
    })
    
  },

  // 返回首页
  returnIndex: function () {
    wx.navigateBack({
      url: '../live-list/live-list'
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
  
    wx.request({
      url: app.pageConfig.jnbyUrl +'/sunday/small/member/findOne',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        memberId: options.memberId
      },
      success: function (res) {
        let userInfor = res.data.result
        console.log('userInfor')
        console.log(userInfor)
        // 获取聊天室服务端地址
        wx.request({
          url: app.pageConfig.requestChatroomServerAddress,
          data: {
            netId: userInfor.netId,
            roomId: options.roomId
          },
          header: {
            "Content-Type": "application/x-www-form-urlencoded",
            appkey: app.pageConfig.appkey
          },
          method: 'POST',
          success: (res) => {
            console.log(res.data.result.addr)
            let addr = res.data.result.addr
            app.chatroomServer = addr
            // 获取指定聊天室实例
            let chatroomInstance = Chatroom.getInstance({
              appKey: app.pageConfig.appkey,
              // account: app.globalData.account,
              account: userInfor.netId,
              // account: '122',
              // // token: app.globalData.password,
              token: userInfor.token,
              // token: '92692ed86723f2d44e1ddaece31197ae',
              reconnectionAttempts: 10,
              chatroomId: options.roomId,
              chatroomAddresses: addr,
              onconnect: self.onChatroomConnect,
              onerror: self.onChatroomError,
              onwillreconnect: self.onChatroomWillReconnect,
              ondisconnect: self.onChatroomDisconnect,
              onmsgs: self.onChatroomMsgs
            });
            // 暂存聊天室实例
            app.chatroomInstance = chatroomInstance
          }
        })

       

        self.setData({
          userInfor: userInfor
        })


      },
      complete: function () {
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }
    })


    // 直播部分
    self.setData({
      src: options.src,
      liveId: options.liveId,
      roomId: options.roomId,
      accountName: options.accountName,
      accountImage: options.accountImage,
      memberId: options.memberId,
      scoreTime: options.scoreTime,
      integeral: options.integeral
    })
    self.createContext();
    // 直播部分end
    
    
    // 寻找聊天室贴图
    let charroomImageIndex = null
    let chatroomList = app.chatroomList
    chatroomList.map((item, index) => {
      if (item.roomid == options.roomId) {
        charroomImageIndex = index
        return
      }
    })

    // 判断系统
    wx.getSystemInfo({
      success: function (res) {
        if (res.model.indexOf('iPhone') !== -1) {
          self.setData({
            cursorSpacingB: true
          })
        }
      }
    })

    // 设置顶部标题
    wx.setNavigationBarTitle({
      title: options.name,
    })

    // 获取积分
    clearTimeout(integralTimeout)
    integralTimeout = setTimeout(function () {
      self.getIntegralF();
    }, options.scoreTime * 60 * 1000)
    

    
    this.setData({
      animation: wx.createAnimation({
        duration: 1000,
        timingFunction: 'ease',
      }),
      messageWrapperMaxHeight: wx.getSystemInfoSync().windowHeight - 40 - 54,
      // messageWrapperMaxHeight: wx.getSystemInfoSync().windowHeight - 275 - 40,
      defaultAvatar: app.pageConfig.defaultAvatar,
      iconBase64Map: iconBase64Map,
      roomInfo: Object.assign({}, app.chatroomList[charroomImageIndex], {
        roomImage: app.pageConfig.chatroomImageBaseUrl + 'image' + charroomImageIndex + '.png',
        onlineusercount: +app.chatroomList[charroomImageIndex].onlineusercount + 1, // 自己进去了
      })
    })
  },

  
  // 生命周期函数--监听页面初次渲染完成
  onReady: function () {
    var that = this;
      // 直播部分
      that.createContext();
      wx.setKeepScreenOn({
        keepScreenOn: true,
      })
    // 直播部分end

  },

  // 生命周期函数--监听页面显示
  onShow: function () {
    var that = this;
      // 直播部分
      // this.play()
      wx.setKeepScreenOn({
        keepScreenOn: true
      })
    // 直播部分end

    // 创建webSocket
    if (!socketOpen) {
      that.webSocket()
    }

    // 获取商品
    that.getGoods();


    // 初始化点赞数和在线人数
    that.getZanOnlineNumstart();

    // 获取点赞数和在线人数(每隔10s获取一次)
    clearInterval(goodsInterval);
    goodsInterval = setInterval(function () {
      that.getGoods();
      that.getZanOnlineNum();
    }, 10000)

    that.openLive();
    

    SocketTask2.onOpen(res => {
      socketOpen = true;
      console.log('监听 WebSocket 连接打开事件。', res)
    })
    SocketTask2.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
      // that.webSocket()
    })
    SocketTask2.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      socketOpen = false
      // that.webSocket()
    })

    SocketTask2.onMessage(onMessage => {
      // console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', JSON.parse(onMessage.data))
      // var onMessage_data = JSON.parse(onMessage.data)
      console.log(onMessage.data)
      var msg = JSON.parse(onMessage.data);
      console.log(msg.rewardId)

      switch (msg.type) {
        case 0:
          console.log('连接消息')
          break;
        case 1:

          break;
        case 2:
          if (msg.liveId == that.data.liveId) {
            that.setData({
              rewardId2: msg.rewardId
            })
            if (!that.data.openGiftB) {
              switch (msg.vouid) {
                case 6530:
                  that.setData({
                    couponAmount: '8折',
                    couponDes: '限购2件商品'
                  })
                  break;
                case 6531:
                  that.setData({
                    couponAmount: '￥500',
                    couponDes: '无门槛代金券'
                  })
                  break;
                case 6532:
                  that.setData({
                    couponAmount: '￥50',
                    couponDes: '满300元使用'
                  })
                  break;
                case 6533:
                  that.setData({
                    couponAmount: '￥100',
                    couponDes: '满1000元使用'
                  })
                  break;
                case 6534:
                  that.setData({
                    couponAmount: '￥200',
                    couponDes: '满2000元使用'
                  })
                  break;
              }
              // console.log(msg.integeral)
              that.setData({
                integralNum2: msg.integeral
              })
              that.giftAnimation()
              console.log('礼包')
            }
          }
          break;
        case 3:
          if (msg.liveId == that.data.liveId) {
            // console.log("vouid"+ msg.vouid)
            that.setData({
              rewardId3: msg.rewardId
            })
            switch (msg.vouid) {
              case 6530:
                if (!that.data.couponB1) {
                  that.setData({
                    couponFlag: false
                  })
                  that.countDown2();
                }
                break;
              case 6531:
                if (!that.data.couponB2) {
                  that.setData({
                    couponFlag: false
                  })
                  that.countDown1();
                }
                break;
              case 6532:
                if (!that.data.couponB3) {
                  that.setData({
                    couponFlag: false
                  })
                  that.countDown3();
                }
                break;
              case 6533:
                if (!that.data.couponB4) {
                  that.setData({
                    couponFlag: false
                  })
                  that.countDown4();
                }
                break;
              case 6534:
                if (!that.data.couponB5) {
                  that.setData({
                    couponFlag: false
                  })
                  that.countDown5();
                }
                break;
            }
            console.log('优惠券')
          }
          break;
      }

    })
    
  },

  onHide: function () {
    clearTimeout(integralTimeout)
    clearInterval(goodsInterval);
    SocketTask2.close(function (close) {
      console.log('关闭 WebSocket 连接。', close)
      socketOpen = false
    })
    
  },

  /**
   * 页面卸载清除聊天室实例
   */
  onUnload() {
    clearTimeout(integralTimeout)
    clearInterval(goodsInterval);
    SocketTask2.close(function (close) {
      console.log('关闭 WebSocket 连接。', close)
      socketOpen = false
    })
    if (app.chatroomInstance) {
      app.chatroomInstance.destroy({
        done: () => {
          app.chatroomInstance = null
          app.inChatroom = false
          console.log('退出聊天室')
        }
      })
    } else {
      app.chatroomInstance = null
      app.inChatroom = false
    }

    // 直播
    this.stop()
    wx.setKeepScreenOn({
      keepScreenOn: false,
    })
    // 直播end
  },
  pageTimer: null,
  getChatroomMembers() {
    let self = this
    // 拉取成员信息
    app.chatroomInstance.getChatroomMembers({
      guest: false,
      done: (error, obj) => {
        if (error) {
          console.log(error)
          return
        }
        self.mergeOnlineMember(obj.members)
      }
    })
    app.chatroomInstance.getChatroomMembers({
      guest: true,
      done: (error, obj) => {
        if (error) {
          console.log(error)
          return
        }
        self.mergeOnlineMember(obj.members)
      }
    })
  },
  /**
   * 连接上服务器
   */
  onChatroomConnect(chatroomInfo) {
    // console.log('onChatroomConnect', chatroomInfo)
    this.getChatroomMembers()
  },
  /**
   * 收到消息
   * [{attach: {from,fromNick,gaged,tempMuteDuration,tempMuted,to:[],toNick:[],type},chatroomId,flow,from,custom,content,fromClientType,fromCustom,resend,idClient,status,text,time,type}]
   */
  onChatroomMsgs(msgs) {
    console.log('onChatroomMsgs', msgs)
    let self = this
    msgs.map(msg => {
      switch (msg.type) {
        case 'notification': {
          self.addNotificationToRender(msg)
          console.log('msg')
          console.log(msg)
          break
        }
        case 'text': {
          self.addTextToRender(msg)
          break
        }
        case 'image': {
          self.addImageToRender(msg)
          break
        }
        case 'custom': {
          self.addCustomMsgToRender(msg)
          break
        }
        case 'robot': {

        }
        default: {
          self.addOtherMsgToRender(msg)
          break
        }
      }
    })
    // 滚动到底部
    self.scrollToBottom()
  },
  /**
   * 发生错误
   */
  onChatroomError(error, obj) {
    console.log('onerror', error, obj);
    this.toastAndBack()
  },
  /**
   * 即将重连
   */
  onChatroomWillReconnect(obj) {
    // app.globalData.reconnectionAttempts++
    // if (app.globalData.reconnectionAttempts == 10) {
    //   app.globalData.reconnectionAttempts = 0
    //   this.toastAndBack()
    // }
    console.log(`onwillreconnect-${app.reconnectionAttempts}`, obj);
  },
  /**
   * 已经断开连接
   */
  onChatroomDisconnect(error) {
    console.log('ondisconnect', error);
    // this.toastAndBack()
  },
  toastAndBack() {
    clearTimeout(this.pageTimer)
    this.pageTimer = setTimeout(() => {
      wx.showToast({
        title: '连接已断开,即将返回',
        duration: 2000,
        success: function () {
          wx.redirectTo({
            url: '/pages/home/home',
          })
        }
      })
    }, 200)
  },
  /**
   * 添加文本(包含emoji)消息到渲染队列中
   */
  addTextToRender(msg) {
    // 刷新界面
    var that = this
    let displayTimeHeader = formatTime(msg.time)
    if (that.data.messageArr.length > 4) {
      that.data.messageArr.splice(0, that.data.messageArr.length - 4)
    }
    this.setData({
      messageArr: [...this.data.messageArr, {
        account: msg.from,
        nick: msg.fromNick,
        text: msg.text,
        type: msg.type,
        time: msg.time,
        displayTimeHeader,
        nodes: generateRichTextNode(msg.text)
      }]
    })
    // console.log(that.data.messageArr)
  },
  /**
   * 添加图片消息到渲染队列中
   */
  addImageToRender(msg) {
    // 添加到渲染队列
    let displayTimeHeader = formatTime(msg.time)
    this.setData({
      inputValue: '',
      messageArr: [...this.data.messageArr, {
        account: msg.from,
        nick: msg.fromNick,
        text: msg.text,
        file: msg.file, // image消息才有此字段
        type: msg.type, // "image"
        time: msg.time,
        displayTimeHeader,
        nodes: generateImageNode(msg.file)
      }]
    })
  },
  /**
   * 添加通知消息到渲染队列中
   */
  addNotificationToRender(msg) {
    // 添加到渲染队列
    let displayTimeHeader = formatTime(msg.time)
    this.setData({
      messageArr: [...this.data.messageArr, {
        account: msg.from,
        nick: msg.attach.fromNick,
        text: msg.text,
        type: msg.attach.type, // "memberEnter"、"memberExit"
        time: msg.time,
        displayTimeHeader,
        nodes: []
      }]
    })
    // 新增或删除在线成员
    let onlineMember = []
    if (msg.attach.type == 'memberEnter') {
      onlineMember = [...this.data.onlineMember]
      onlineMember.push({
        account: msg.from,
        avatar: '',
        nick: msg.attach.fromNick,
        type: 'guest'
      })
    } else if (msg.attach.type == 'memberExit') {
      this.data.onlineMember.map(member => {
        if (msg.from != member.account) {
          onlineMember.push(member)
        }
      })
    }
    this.setData({
      onlineMember
    })
  },
  /**
   * 添加自定义消息到渲染队列中
   */
  addCustomMsgToRender(msg) {
    // 添加到渲染队列
    let displayTimeHeader = formatTime(msg.time)
    let customContent = JSON.parse(msg['content'])
    let renderType = 'custom'
    if (customContent.type == 1) {
      renderType = '猜拳'
    }
    this.setData({
      messageArr: [...this.data.messageArr, {
        account: msg.from,
        nick: msg.fromNick,
        text: msg.text,
        content: msg.content, // 自定义消息才有此字段
        type: renderType, // "custom"、猜拳
        time: msg.time,
        displayTimeHeader,
        nodes: generateImageNode(generateFingerGuessImageFile(customContent.data.value))
      }]
    })
  },
  /**
   * 添加其他类型消息到渲染队列
   */
  addOtherMsgToRender(msg) {
    // 添加到渲染队列
    let displayTimeHeader = formatTime(msg.time)
    this.setData({
      inputValue: '',
      messageArr: [...this.data.messageArr, {
        account: msg.from,
        nick: msg.fromNick || '',
        text: msg.text,
        type: msg.type,
        time: msg.time,
        displayTimeHeader,
        nodes: [{
          type: 'text',
          text: `暂不支持该类型消息,请到手机或电脑客户端查看！`
        }]
      }]
    })
  },
  refreshRoomInfo(roomInfo) {
    this.setData({
      roomInfo: Object.assign({}, this.data.roomInfo, {
        onlineusercount: roomInfo.onlineMemberNum
      })
    })
  },
  /**
   * nav点击
   */
  switchNav(e) {
    let self = this
    if (this.data.currentTab == e.currentTarget.dataset.current) {
      return
    } else {
      this.setData({
        currentTab: e.currentTarget.dataset.current
      })
      if (e.currentTarget.dataset.current == 2) {
        // 清除上次数据
        self.setData({
          accountMap: {},
          onlineMember: []
        })
        // 刷新在线成员
        this.getChatroomMembers()
      } else if (e.currentTarget.dataset.current == 1) {
        // 刷新在线人数
        app.chatroomInstance.getChatroom({
          done: function (err, obj) {
            if (err) {
              console.log(err)
              return
            }
            self.refreshRoomInfo(obj.chatroom)
          }
        });
      }
    }
  },
  /**
   * 转化消息类型
   */
  converMemberType(memberType) {
    switch (memberType) {
      case 'owner':
        return '房主'
      case 'manager':
        return '管理员'
      case 'restricted':
        return '受限制, 被拉黑或者禁言'
      case 'common':
        return '普通成员'
      case 'guest':
        return '游客'
    }
  },
  /**
   * 合并在线在线用户信息
   */
  mergeOnlineMember(memberArr) {
    let result = [...this.data.onlineMember]
    let accountMap = Object.assign({}, this.data.accountMap) // 目的是去重
    memberArr.map(member => {
      // 在线成员
      if (member.online == true && !accountMap[member.account]) {
        accountMap[member.account] = member.account
        result.push(Object.assign({}, member, {
          avatar: member.avatar,
          type: this.converMemberType(member.type)
        }))
      }
      // 主播
      if (member.type == 'owner') {
        this.setData({
          ownerInfo: Object.assign({}, member)
        })
      }
    })

    this.setData({
      accountMap,
      onlineMember: result
    })
  },
  /**
   * 阻止事件冒泡空函数
   */
  stopEventPropagation() {
  },
  /**
   * 滚动页面到底部
   */
  scrollToBottom() {
    let self = this
    wx.createSelectorQuery().select('#recordWrapper').boundingClientRect(function (rect) {
      if (rect.bottom > self.data.messageWrapperMaxHeight) {
        self.setData({
          scrollTop: 9999999
        })
      }
    }).exec()
  },
  /**
   * 输入事件
   */
  inputChange(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  /**
   * 获取焦点
   */
  inputFocus(e) {
    var cursorSpacing = e.detail.height;
    this.setData({
      emojiFlag: false,
      focusFlag: true,
      cursorSpacing: cursorSpacing
    })
  },
  /**
   * 失去焦点
   */
  inputBlur() {
    this.setData({
      focusFlag: false
    })
  },
  /**
   * 切换出emoji键盘
   */
  toggleEmoji() {
    this.setData({
      emojiFlag: !this.data.emojiFlag,
      moreFlag: false
    })
  },
  /**
   * 切出更多
   */
  toggleMore() {
    this.setData({
      moreFlag: !this.data.moreFlag,
      emojiFlag: false,
      focusFlag: false
    })
  },
  /**
   * emoji组件回调
   */
  emojiCLick(e) {
    let val = e.detail
    // 单击删除按钮，，删除emoji
    if (val == '[删除]') {
      let lastIndex = this.data.inputValue.lastIndexOf('[')
      if (lastIndex != -1) {
        this.setData({
          inputValue: this.data.inputValue.slice(0, lastIndex)
        })
      }
      return
    }
    if (val[0] == '[') { // emoji
      this.setData({
        inputValue: this.data.inputValue + val
      })
    }
  },
  /**
   * emoji点击发送
   */
  emojiSend(e) {
    let val = this.data.inputValue
    this.sendRequest(val)
    this.setData({
      emojiFlag: false
    })
  },
  /**
   * 发送文本
   */
  inputSend(e) {
    let text = e.detail.value
    this.sendRequest(text)
  },
  /**
   * 选择相册图片
   */
  chooseImageToSend(e) {
    let type = e.currentTarget.dataset.type
    let self = this
    self.setData({
      moreFlag: false
    })
    wx.chooseImage({
      sourceType: ['album'],
      success: function (res) {
        self.sendImageToNOS(res)
      },
    })
  },
  /**
   * 发送网络请求：发送文字
   */
  sendRequest(text) {
    let self = this
    this.setData({
      inputValue: ''
    })
    app.chatroomInstance.sendText({
      text,
      done: (err, msg) => {
        if (err) {
          console.log(err)
          return
        }
        // 刷新界面
        self.addTextToRender(msg)
        // 滚动到底部
        self.scrollToBottom()
      }
    })
  },
  /**
   * 发送自定义消息-猜拳
   */
  sendFingerGuess() {
    let self = this
    self.setData({
      moreFlag: false
    })
    let content = {
      type: 1,
      data: {
        value: Math.ceil(Math.random() * 3)
      }
    }
    app.chatroomInstance.sendCustomMsg({
      content: JSON.stringify(content),
      done: function (err, msg) {
        if (err) {
          console.log(err)
          return
        }
        // 刷新界面
        self.addCustomMsgToRender(msg)
        // 滚动到底部
        self.scrollToBottom()
      }
    })
  },
  /**
   * 发送图片到nos
   */
  sendImageToNOS(res) {
    wx.showLoading({
      title: '发送中...',
    })
    let self = this
    let tempFilePaths = res.tempFilePaths
    for (let i = 0; i < tempFilePaths.length; i++) {
      // 上传文件到nos
      app.chatroomInstance.sendFile({
        type: 'image',
        wxFilePath: tempFilePaths[i],
        done: function (err, msg) {
          wx.hideLoading()
          if (err) {
            console.log(err)
            return
          }
          // 刷新界面
          self.addImageToRender(msg)
          // 滚动到底部
          self.scrollToBottom()
        }
      })
    }
  },


  // 以下是直播部分
  createContext: function () {
    this.setData({
      livePlayerContext: wx.createLivePlayerContext('livePlayer')
    })
  },
  inputSrc: function (e) {
    this.checkUrl(e.detail.value)
    console.log(e.detail.value)
    this.setData({
      src: e.detail.value
    })
    this.createContext();
  },
  scanQRCode: function () {
    var that = this
    that.data.livePlayerContext.stop()
    wx.scanCode({
      success: function (res) {
        console.log(res)
        if (res.scanType === 'QR_CODE' && res.errMsg === 'scanCode:ok') {
          that.createContext();
          that.setData({
            src: res.result
          })
        } else {
          wx.showToast({
            image: '/res/img/err_icon.png',
            title: '获取地址失败'
          })
        }
      }
    })
  },
  checkUrl: function (str) {
    if (/^(rtmp|RTMP):\/\/[\w\/\.?&_=-]+$/.test(str) || /^(http|HTTP|https|HTTPS):\/\/[\w\/\.&_=-]+\.flv[\w\/\.=?&_-]*$/.test(str)) {
      return true
    }
    wx.showToast({
      image: '/res/img/err_icon.png',
      title: '不可用的地址'
    })
    return false
  },
  play: function () {
    if (!this.checkUrl(this.data.src)) {
      return
    }
    var that = this
    this.data.livePlayerContext.play({
      success: function (res) {
        that.setData({
          pulling: true
        })
      },
      fail: function (res) {
        wx.showToast({
          image: '/res/img/err_icon.png',
          title: '播放失败'
        })
      }
    })
    that.setData({
      pulling: true
    })
  },
  stop: function () {
    var that = this
    this.data.livePlayerContext.stop({
      success: function (res) {
        that.setData({
          pulling: false
        })
      },
      fail: function (res) {
        wx.showToast({
          image: '/res/img/err_icon.png',
          title: '操作失败'
        })
      }
    })
  },
  pause: function () {
    var that = this
    this.data.livePlayerContext.pause({
      success: function (res) {
        that.setData({
          pulling: false
        })
      },
      fail: function (res) {
        wx.showToast({
          image: '/res/img/err_icon.png',
          title: '操作失败'
        })
      }
    })
  },
  resume: function () {
    var that = this
    this.data.livePlayerContext.resume({
      success: function (res) {
        that.setData({
          pulling: true
        })
      },
      fail: function (res) {
        wx.showToast({
          image: '/res/img/err_icon.png',
          title: '操作失败'
        })
      }
    })
  },
  switchMuted() {
    this.setData({
      muted: !this.data.muted
    })
  },
  switchOrientation() {
    this.setData({
      orientation: this.data.orientation === 'vertical' ? 'horizontal' : 'vertical'
    })
  },
  swicthObjectFit() {
    this.setData({
      objectFit: this.data.objectFit === 'contain' ? 'fillCrop' : 'contain'
    })
  },
  statechange(e) {
    if ([2004].indexOf(+e.detail.code) !== -1) {
      this.setData({
        pulling: true
      })

    }
    if ([2006, 3005].indexOf(+e.detail.code) !== -1) {
      this.setData({
        endB: false
      })
      this.stop()
      setTimeout(function () {
        wx.showToast({
          image: '/res/img/err_icon.png',
          title: '主播停止推流' + e.detail.code
        })
      }, 800)
      
    }
    if ([-2301, 3001, 3002, 3003].indexOf(+e.detail.code) !== -1) {
      this.stop()
      // setTimeout(function () {
      //   wx.showToast({
      //     image: '/res/img/err_icon.png',
      //     title: '播放失败' + e.detail.code
      //   })
      // }, 800)
    }
  },
  fullscreenchange(e) {
    console.log('fullscreenchange: ', e.detail)
  },
  netstatus(e) {
    console.log('live-player info:', e.detail.info)
  },
  error(e) {
    console.error('live-player error:', e.detail.errMsg)
    wx.showToast({
      image: '/res/img/err_icon.png',
      title: '播放失败'
    })
  },

  webSocket: function () {
    // 创建Socket
    
    SocketTask2 = wx.connectSocket({
      url: 'wss://live.jnby.com/websocket',
      data: 'data',
      header: {
        'content-type': 'application/json'
      },
      method: 'post',
      success: function (res) {
        // socketOpen = false
        console.log('WebSocket连接创建', res)
      },
      fail: function (err) {
        wx.showToast({
          title: '网络异常！',
        })
        console.log(err)
      },
    })
  },

  // 获取积分
  getIntegralF: function () {
    let that = this
      console.log(that.data.liveId + '////' + that.data.memberId)
      wx.request({
        url: app.pageConfig.jnbyUrl +'/sunday/small/live/receiveScore',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          liveId: that.data.liveId,
          memberId: that.data.memberId
        },
        success: function (res) {
          if (res.data.code == 0) {
            console.log(that.data.scoreTime + '||' + that.data.integeral)
            if (that.data.scoreTime == 'null' || that.data.scoreTime == '' || that.data.integeral == 'null' || that.data.integeral == ''){
              console.log('无倒计时')
            } else {
              that.setData({
                integralTime: that.data.scoreTime,
                integralNum: that.data.integeral
              })
              
              that.integralAnimation()
            
            }
            console.log('累计时间积分')
          }
          
        },
        fail: function (err) {
          wx.showToast({
            title: '请求失败！',
          })
          console.log(err)
        }
      })
  },

  // 获取礼包
  getGift: function (e) {
    let that = this
    if (that.data.giftFlag) {
      that.setData({
        giftFlag: false
      })
      wx.request({
        url: app.pageConfig.jnbyUrl +'/sunday/small/live/receivePackage',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          // unionId: 'oZpUxs0d3GFdkmeKyQm0XeOe6DFA',
          // openId: 'oB7r0t1hvCWbNUNFodpkP0ee1UpY',
          unionId: that.data.userInfor.weixinUnionId,
          openId: that.data.userInfor.jnbyOpenId,
          rewardId: that.data.rewardId2
        },
        success: function (res) {
          if (res.data.code == 0) {
            that.openGiftShow();
          } else {
            wx.showToast({
              icon: 'none',
              title: '领取失败！',
            })
            that.setData({
              giftB: false
            })
          }
        },
        fail: function (err) {
          wx.showToast({
            title: '请求失败！',
          })
          console.log(err)
        }
      })
    }
  },

  // 获取优惠券
  getCoupon: function (e) {
    let that = this
    var couponIndex = e.currentTarget.dataset.index;
    that.setData({
      couponFlag: true
    })
      wx.request({
        url: app.pageConfig.jnbyUrl +'/sunday/small/live/receivePackage',
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          // unionId: 'oZpUxs0d3GFdkmeKyQm0XeOe6DFA',
          // openId: 'oB7r0t1hvCWbNUNFodpkP0ee1UpY',
          unionId: that.data.userInfor.weixinUnionId,
          openId: that.data.userInfor.jnbyOpenId,
          rewardId: that.data.rewardId3
        },
        success: function (res) {
          if (res.data.code == 0) {
            wx.showToast({
              title: '优惠领取成功!',
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: '已经领完了！',
            })
          }
        },
        fail: function (err) {
          wx.showToast({
            title: '请求失败！',
          })
          console.log(err)
        }
      })
      
  },

  // 获取商品
  getGoods: function () {
    let that = this
    
    wx.request({
      url: app.pageConfig.jnbyUrl +'/sunday/small/live/selectGoods',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        liveId: that.data.liveId,
        "sort": "ct",
        "order": "desc"
      },
      success: function (res) {
        var goods = res.data.result;
        if (that.data.goods && !that.data.addGoodsB){
        var addGoods = goods.length - that.data.goods.length;
        if (addGoods > 0) {
          that.setData({
            addGoodsB: true,
            addGoodsNum: addGoods
          })
          setTimeout(function () {
            that.setData({
              addGoodsB: false
            })
          },3000)
        }
        }
        that.setData({
          goods: goods
        })
        
      },
      fail: function (err) {
        wx.showToast({
          title: '请求失败！',
        })
        console.log(err)
      }
    })
    
  },

  // 初始化点赞数和在线人数
  getZanOnlineNumstart: function () {

    let that = this
    wx.request({
      url: app.pageConfig.jnbyUrl +'/sunday/small/live/findOne',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        liveId: that.data.liveId
      },
      success: function (res) {
        var liveDetails = res.data.result;
        console.log('liveDetails')
        console.log(liveDetails)
        that.setData({
          onlineNum: liveDetails.onlineNum + 1,//把自己也加进去
          zanNum: liveDetails.zanNum
        })
      },
      fail: function (err) {
        wx.showToast({
          title: '请求失败！',
        })
        console.log(err)
      }
    })

  },


  // 获取点赞数和在线人数
  getZanOnlineNum: function () {
    
    let that = this
    wx.request({
      url: app.pageConfig.jnbyUrl +'/sunday/small/live/findOne',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        liveId: that.data.liveId
      },
      success: function (res) {
        var liveDetails = res.data.result;
        console.log('liveDetails')
        console.log(liveDetails)
        that.setData({
          liveDetails: liveDetails,
          onlineNum: liveDetails.onlineNum,
          zanNum: liveDetails.zanNum
        })
      },
      fail: function (err) {
        wx.showToast({
          title: '请求失败！',
        })
        console.log(err)
      }
    })

  },

  // 初始化点赞数和在线人数
  getZanOnlineNumstart: function () {

    let that = this
    wx.request({
      url: app.pageConfig.jnbyUrl + '/sunday/small/live/findOne',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        liveId: that.data.liveId
      },
      success: function (res) {
        var liveDetails = res.data.result;
        console.log('liveDetails')
        console.log(liveDetails)
        that.setData({
          liveDetails: liveDetails,
          onlineNum: liveDetails.onlineNum + 1,//把自己也加进去
          zanNum: liveDetails.zanNum
        })
      },
      fail: function (err) {
        wx.showToast({
          title: '请求失败！',
        })
        console.log(err)
      }
    })

  },


  // 
  openLive: function () {

    let that = this
    wx.request({
      url: app.pageConfig.jnbyUrl + '/sunday/small/live/openLive',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        liveId: that.data.liveId,
        memberId: that.data.memberId
      },
      success: function (res) {
        
      },
      fail: function (err) {
        wx.showToast({
          title: '请求失败！',
        })
        console.log(err)
      }
    })

  },

  /**
    * 用户点击右上角分享
    */
  onShareAppMessage: function () {
    var that = this
    return {
      title: '江南布衣',
      imageUrl: that.data.liveDetails.image,
      path: '/pages/live-list/live-list'
    }
  }
})